home *** CD-ROM | disk | FTP | other *** search
- Path: newsfeed.internetmci.com!xmission!news
- From: tknarr@xmission.com ( Todd Knarr )
- Newsgroups: comp.lang.c++
- Subject: Re: two tricky questions
- Date: 31 Dec 1995 21:28:30 GMT
- Organization: Chaos Central
- Message-ID: <4c6v9u$jdl@news.xmission.com>
- References: <4c4tbn$ga9@sunburst.ccs.yorku.ca> <4c5dn1$j5r@news.xmission.com>
- Reply-To: tknarr@xmission.com ( Todd Knarr )
- NNTP-Posting-Host: slc149.xmission.com
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4c4tbn$ga9@sunburst.ccs.yorku.ca>, cs932082@ariel.cs.yorku.ca (Lila Behzadi) writes:
- >if I add "a=0" in the defult constructor of class A ; I will get the
- >following output and the problem will be solved:
-
- It turns out there's another potential problem I overlooked. You do not
- define a copy constructor, so the compile will generate one that does a
- memberwise ( or bitwise ) assignment of the original to the copy. This is
- not good, because after this both the original and the copy have pointers
- to the same memory in them. When the original is destroyed that memory
- will be freed by delete, leaving a dangling pointer in the copy to foul
- up both references to it *and* the delete when the copy is destroyed. It
- is legal for the compiler, in your code, to create a temporary and initialize
- aaa via the copy constructor ( stupid, but legal ), leaving you deleting
- the same memory twice.
-
- In general, I've found that classes that allocate dynamic memory and use
- pointers to it also need non-trivial copy constructors and copy assignment
- operators to avoid exactly this sort of problem.
-
- --
- Todd Knarr : tknarr@xmission.com | finger for PGP public key
- | Member, USENET Cabal
-
- Seriously, I don't want to die just yet. I don't care how
- good-looking they are, I! don't! want! to! die!"
- -- Megazone ( UF1 )
-
-